package com.vecspace.datacenter.datatransform.service;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import com.vecspace.database.model.ConnectionParam;
import com.vecspace.utils.log.HLogger;

/**
 * 
 * @author: wanghua
 */
public abstract class Database2DatabaseETL extends DataETL{

	private ConnectionParam srcConnParam;
	private ConnectionParam dstConnParam;
	
	@Override
	public boolean execute(String args) {
		Connection srcConn = null, dstConn = null;		
		try{
			srcConn = this.getSrcConnection();
			dstConn = this.getDstConnection();
			return doDataETL(srcConn, dstConn, args);
		}catch(Exception ex){
			HLogger.DEFAULT().error(ex);
			return false;
		}
		finally{
			try {
				if(srcConn != null){
					srcConn.close();
					srcConn = null;
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			
			try {
				if(dstConn != null){
					dstConn.close();
					dstConn = null;
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}		
	}
	
	/**执行ETL作业
	 * 建议使用DbUtils工具类进行数据库操作。
	 * @param srcConn 来源数据库（使用完后不需要close）
	 * @param dstConn 目的数据库（使用完后不需要close）
	 * @throws Exception 
	 * @author: wanghua
	 */
	public abstract boolean doDataETL(Connection srcConn, Connection dstConn, String args) throws Exception;
	
	/**
	 * 
	 * 功能描述：
	 * @return
	 * @throws Exception 
	 * @author: wanghua
	 */
	protected Connection getSrcConnection() throws Exception{
		ConnectionParam connparam = srcConnParam;
		Class.forName(connparam.getDriverClassName());
		Connection conn = DriverManager.getConnection(connparam.getUrl(),connparam.getUserId(),connparam.getPassword());
		return conn;
	}

	/**
	 * 
	 * 功能描述：
	 * @return
	 * @throws Exception 
	 * @author: wanghua
	 */
	protected Connection getDstConnection() throws Exception{
		ConnectionParam connparam = dstConnParam;
		Class.forName(connparam.getDriverClassName());
		Connection conn = DriverManager.getConnection(connparam.getUrl(),connparam.getUserId(),connparam.getPassword());
		return conn;
	}

	public ConnectionParam getSrcConnParam() {
		return srcConnParam;
	}

	public void setSrcConnParam(ConnectionParam srcConnParam) {
		this.srcConnParam = srcConnParam;
	}

	public ConnectionParam getDstConnParam() {
		return dstConnParam;
	}

	public void setDstConnParam(ConnectionParam dstConnParam) {
		this.dstConnParam = dstConnParam;
	}
}
